package br.com.foxinline.manager.criar;

import br.com.foxinline.modelo.*;
import br.com.foxinline.servico.*;
import br.com.foxinline.util.Conexao;
import br.com.foxinline.util.Msg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.event.map.MarkerDragEvent;
import org.primefaces.event.map.PointSelectEvent;
import org.primefaces.event.map.StateChangeEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.Marker;
import org.primefaces.model.map.Polygon;
import org.primefaces.model.map.Polyline;

/**
 *
 * @author laverson
 */
@ViewScoped
@ManagedBean
public class ManagerCriarSetor implements Serializable {

    @EJB
    SetorServico setorServico;
    @EJB
    BairroServico bairroServico;
    @EJB
    PrefeituraServico prefeituraServico;
    private Setor setor;
    private DefaultMapModel mapModel;
    private List<Coordenada> coordenadas;
    private Coordenada coordenada;
    private Polygon polygon;
    private String centroMapa;
    private int zoomLevelMapa;
    private boolean connect;

    @PostConstruct
    public void init() {

        this.centroMapa = prefeituraServico.getCentroMapa();
        this.zoomLevelMapa = prefeituraServico.getZoomMapa();

        this.setor = new Setor();
        this.coordenada = new Coordenada();
        this.coordenadas = new ArrayList<Coordenada>();
        this.mapModel = new DefaultMapModel();
        this.polygon = new Polygon();

        if (prefeituraServico.find().getDesabilitarMapas()) {

            this.connect = false;
        } else if (!Conexao.isInternetReachable()) {

            this.connect = false;
            Msg.messagemWarn("Não foi possível estabelecer uma conexão com a Internet.");
        } else {
            this.connect = true;
            loadMap();
        }
    }

    private void loadMap() {
        mapModel = new DefaultMapModel();
        Polyline polyline;
        LatLng coord;

        for (Bairro bairro : bairroServico.findAll()) {

            coordenadas = bairroServico.lstCoordenadaBairro(bairro);
            polyline = new Polyline();

            for (Coordenada c : coordenadas) {
                coord = new LatLng(c.getLat(), c.getLog());

                polyline.getPaths().add(coord);

                polyline.setStrokeColor("#1B93DF");
                polyline.setStrokeWeight(2);
            }

            if (coordenadas != null && !coordenadas.isEmpty()) {
                coord = new LatLng(coordenadas.get(0).getLat(), coordenadas.get(0).getLog());
                polyline.getPaths().add(coord);
            }

            mapModel.addOverlay(polyline);
        }
    }

    public void handlePointClick(PointSelectEvent event) {

        LatLng latLng = event.getLatLng();

        addOverlayToMapModel(new Marker(latLng));

        this.mapModel.addOverlay(this.polygon);

        for (Marker premarker : this.mapModel.getMarkers()) {
            premarker.setDraggable(true);
        }

    }

    private void addOverlayToMapModel(Marker marker) {

        if (marker.getData() == null || !marker.getData().equals(Quadra.class.getSimpleName())) {
            this.mapModel.addOverlay(marker);
            this.polygon.getPaths().add(marker.getLatlng());
            this.polygon.setStrokeColor("#FF9900");
            this.polygon.setFillColor("#FF9900");
            this.polygon.setFillOpacity(0.1);
        }
    }

    public void onMarkerDrag(MarkerDragEvent event) {

        Marker marker = event.getMarker();

        if (marker.getData() instanceof Coordenada
                && this.coordenadas.contains((Coordenada) marker.getData())) {

            int index = this.coordenadas.indexOf((Coordenada) marker.getData());

            Coordenada c = this.coordenadas.get(index);
            c.setLat(marker.getLatlng().getLat());
            c.setLog(marker.getLatlng().getLng());
            this.coordenadas.set(index, c);
        }

        for (Marker m : this.mapModel.getMarkers()) {
            if (marker.getId().equals(m.getId())) {
                m.setLatlng(marker.getLatlng());
                break;
            }
        }

        this.polygon = new Polygon();

        List<Marker> markers = this.mapModel.getMarkers();
        loadMap();

        for (Marker m : markers) {
            addOverlayToMapModel(m);
        }

        this.mapModel.addOverlay(this.polygon);

        for (Marker premarker : this.mapModel.getMarkers()) {
            premarker.setDraggable(true);
        }
    }

    public void salvar() {
        try {

            for (Marker marker : this.mapModel.getMarkers()) {
                this.coordenada = new Coordenada();
                this.coordenada.setLat(marker.getLatlng().getLat());
                this.coordenada.setLog(marker.getLatlng().getLng());
                this.coordenadas.add(this.coordenada);
            }

            this.setor.setCoordenadas(this.coordenadas);
            setorServico.save(this.setor);

            init();
            Msg.messagemInfo(Msg.SuccessFull);

        } catch (EJBException e) {

            Exception causedByException = e.getCausedByException();

            if (!(causedByException instanceof javax.validation.ConstraintViolationException)) {
                Msg.messagemError("Já existe um setor com esse número !");
            } else {
                System.err.println(e);
                Msg.messagemError(Msg.Failure);
            }

        } catch (Exception e) {

            System.err.println(e);
            Msg.messagemError(Msg.Failure);
        }
    }

    public void removerMarkers() {
        this.mapModel = new DefaultMapModel();
        this.coordenadas = new ArrayList<Coordenada>();
        this.polygon = new Polygon();
    }

    public void onStateChange(StateChangeEvent event) {
        this.zoomLevelMapa = event.getZoomLevel();
        this.centroMapa = event.getCenter().getLat() + ", " + event.getCenter().getLng();
    }

    public DefaultMapModel getMapModel() {
        return mapModel;
    }

    public void setMapModel(DefaultMapModel mapModel) {
        this.mapModel = mapModel;
    }

    public Setor getSetor() {
        return setor;
    }

    public void setSetor(Setor setor) {
        this.setor = setor;
    }

    public List<Coordenada> getCoordenadas() {
        return coordenadas;
    }

    public void setCoordenadas(List<Coordenada> coordenadas) {
        this.coordenadas = coordenadas;
    }

    public Coordenada getCoordenada() {
        return coordenada;
    }

    public void setCoordenada(Coordenada coordenada) {
        this.coordenada = coordenada;
    }

    public String getCentroMapa() {
        return centroMapa;
    }

    public void setCentroMapa(String centroMapa) {
        this.centroMapa = centroMapa;
    }

    public int getZoomLevelMapa() {
        return zoomLevelMapa;
    }

    public void setZoomLevelMapa(int zoomLevelMapa) {
        this.zoomLevelMapa = zoomLevelMapa;
    }

    public boolean isConnect() {
        return connect;
    }

    public void setConnect(boolean connect) {
        this.connect = connect;
    }
}
